/*
 * Copyright (c) 2015. For Intelligent Group.
 */

package com.intelligent.ispc.foundation.rutils;

import com.intelligent.ispc.foundation.io.ResourceFinder;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.SystemConfiguration;
import org.apache.commons.configuration.XMLConfiguration;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Peter.Li on 2015/10/28.
 */
final class RConfigurationUtils {
    /**
     * Default port for Rserve process if one was not specified.
     */
    static final int DEFAULT_RSERVE_PORT = 6311;

    /**
     * Name of the system environment property that will set a configuration file to use.
     * {@link #DEFAULT_XML_CONFIGURATION_FILE} will be used if this property is not set.
     */
    private static final String DEFAULT_CONFIGURATION_KEY = "RConnectionPool.configuration";

    /**
     * Name of the default configuration file if one is not specified in the environment.
     */
    private static final String DEFAULT_XML_CONFIGURATION_FILE = "RConnectionPool.xml";

    private RConfigurationUtils() {
        super();
    }

    /**
     * Gets the configuration for the RServe processes.
     *
     * @return The RConnectionPool configuration.
     * @throws ConfigurationException if the configuration cannot be built from the url
     *                                returned by {@link #getConfigurationURL()}
     */
    static XMLConfiguration getConfiguration() throws ConfigurationException {
        return new XMLConfiguration(getConfigurationURL());
    }

    /**
     * Gets the configuration for the RServe processes.
     *
     * @return A url that for the RConnectionPool configuration file.
     */
    static URL getConfigurationURL() {
        URL poolConfigURL; // if the user defined a configuration, use it
        final ResourceFinder resourceFinder = new ResourceFinder(".", "config");
        final Configuration systemConfiguration = new SystemConfiguration();
        if (systemConfiguration.containsKey(DEFAULT_CONFIGURATION_KEY)) {
            final String poolConfig = systemConfiguration.getString(DEFAULT_CONFIGURATION_KEY);
            try {
                // First see if we have a URL from the system configuration
                poolConfigURL = new URL(poolConfig);
            } catch (MalformedURLException e) {
                // resource is not a URL, attempt to get the resource from the class path
                poolConfigURL = resourceFinder.findResource(poolConfig);
            }
        } else {
            poolConfigURL = resourceFinder.findResource(DEFAULT_XML_CONFIGURATION_FILE);
        }
        return poolConfigURL;
    }
}
